<?php

class PHPExcelInput{
	private static $objPHPExcel = null;

	function __construct(){
		date_default_timezone_set('Asia/Shanghai');
	}

	public static function getInstance($inputFileName){
		include_once ('../library/PHPExcel.php');
		$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
		return self::$objPHPExcel;
	}

	public static function getSheetData($fileFieldName,$inputFileName){
		move_uploaded_file($_FILES[$fileFieldName]['tmp_name'],$inputFileName);
		self::getInstance($inputFileName);
		$sheetData = self::$objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
		$sheetData = array_slice($sheetData, 1);
		return $sheetData;
	}

	public static function createDir($upload_dir,$site_url,$app_path, $errUrl){
		$dirArr     = explode('/',$upload_dir);
		$uploadsDir = '';
		$depth      = count($dirArr);
		//确定存放文件的文件夹存在
		for ($i=0; $i < $depth; $i++) {
			$uploadsDir .= $dirArr[$i]."/";
			if (!is_dir($app_path . $uploadsDir)) {
				@mkdir($app_path . $uploadsDir, 0777) or 
					header("Location: ".$site_url.$errUrl."新建文件夹".$uploadsDir."失败");
			}
		}
		//确定存放文件的文件夹存在
		if (!is_dir($upload_dir)) {
			@mkdir($upload_dir, 0777) or 
				header("Location: ".$site_url.$errUrl."新建文件夹失败");
		}
		return $upload_dir;
	}

	public static function getError($post, $fileFieldName, $site_url,$errUrl){
		$php_errors = array(1 => '文件过大，请重新上传',
							2 => '文件过大，请重新上传',
							3 => '文件不能完整上传',
							4 => '没有文件被选中');
		//允许上传的文件后缀名
		$fileExt = array("xls", "xlsx");

		//确定文件是否上传成功
		($post[$fileFieldName]['error']==0) or
			header("Location: ".$site_url.$errUrl.
				$php_errors[$_FILES[$fileFieldName]['error']]);

		//判断是否是上传的文件
		@is_uploaded_file($_FILES[$fileFieldName]['tmp_name']) or 
			header("Location: ".$site_url.$errUrl."上传错误文件".$_FILES[$fileFieldName]['tmp_name']);

		//判断文件类型
		if(!in_array(strtolower(substr(strrchr($_FILES[$fileFieldName]['name'], '.'), 1)),$fileExt)){   
			   $text=implode(",",$fileExt);
			   header("Location: ".$site_url.$errUrl."您只能上传以下类型文件: ".$text);
		}
	}

	public static function renameFile($upload_dir, $fileFieldName){
		//文件重命名
		$now = time();
		while(file_exists($fileName=$upload_dir.$now.'-'.$_FILES[$fileFieldName]['name'])) {
			$now++;
		}
		return $fileName;
	}
}

?>